package com.ztewatch.wearcontacts.view;

import java.io.InputStream;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ztewatch.wearcontacts.R;
import com.ztewatch.wearcontacts.loader.ContactsListLoader;

public class ContactListAdapter extends CursorAdapter {

	Context mContext = null;
	LayoutInflater mInflater;

	@SuppressWarnings("deprecation")
	public ContactListAdapter(Context context, Cursor c) {
		super(context, c);
		mContext = context;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		final TextView name_tv = (TextView) view.findViewById(R.id.item_text);
		final ImageView photo = (ImageView) view.findViewById(R.id.item_image);

		if (cursor != null) {
			String name = cursor.getString(ContactsListLoader.NAME_COLUMN_ID);
//			int id = cursor.getInt(ContactsListLoader.ID_COLUMN_ID);
			// String number =
			// cursor.getString(ContactsListLoader.NUMBER_COLUMN_ID);
			name_tv.setText(name);
//			if (context.getResources().getString(R.string.history_str)
//					.equals(name)
//					&& id == 0) {
//				name_tv.setEnabled(false);
//				photo.setEnabled(false);
//				// view.setOnClickListener(null);
//			} else {
//				name_tv.setEnabled(true);
//				photo.setEnabled(true);
//			}
			bindContactPhoto(photo, cursor);
		}
	}

	private void bindContactPhoto(ImageView photo, Cursor cursor) {
		long photoId = 0;
		int index = cursor.getColumnIndex(Data.PHOTO_ID);
		if (index != -1) {
			photoId = cursor.getLong(index);
		}
		if (photoId != 0) {
			int id_index = cursor.getColumnIndex(Data.RAW_CONTACT_ID);
			if (id_index != -1) {
				Long contactID = cursor.getLong(id_index);
				Uri uri = ContentUris.withAppendedId(
						ContactsContract.Contacts.CONTENT_URI, contactID);
				InputStream input = ContactsContract.Contacts
						.openContactPhotoInputStream(
								mContext.getContentResolver(), uri);
				photo.setImageBitmap(BitmapFactory.decodeStream(input));
			}
		} else {
			photo.setImageResource(R.drawable.ic_address_portrait);
		}
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		return mInflater.inflate(R.layout.grid_item, parent, false);
	}
}
